package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import sun.security.provider.MD5;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 登录
     * @param request
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee){
        //将传过来的密码进行加密处理
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //查询数据库 查看用户是否存在
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername,employee.getUsername());
        Employee emp = employeeService.getOne(queryWrapper);

        //判断查询结果
        if (emp == null){
            return R.error("登录失败");
        }
        //比对密码 不相同反馈提示
        if (!emp.getPassword().equals(password)){
            return R.error("登录失败");
        }
        //判断状态是否是禁用 为禁用无法登陆,反馈提示
        if (emp.getStatus() == 0){
            return R.error("账户禁用中");
        }

        //将用户信息存入session
        request.getSession().setAttribute("employee",emp.getId());

        //返回结果 emp
        return R.success(emp);
    }

    /**
     * 员工登出
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        request.getSession().removeAttribute("employee");
        return R.success("登出成功");
    }

    /**
     * 分页展示
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        //新建分页构造器
        Page<Employee> pageInfo = new Page<>(page, pageSize);

        //条件查询
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        //判断如果 name != null ,执行模糊查询   降序排序 修改时间
        queryWrapper.like(StringUtils.isNotEmpty(name),Employee::getName,name)
                .orderByDesc(Employee::getUpdateTime);

        //执行
        employeeService.page(pageInfo,queryWrapper);

        //返回分页构造器
        return R.success(pageInfo);

    }

    @PostMapping
    public R<String> add(HttpServletRequest request,@RequestBody Employee employee){
        log.info("添加员工数据:{}",employee.toString());


        //获取当前登录的用户id
        Long empId = (Long) request.getSession().getAttribute("employee");

        //为用户设置初始密码 123456  并进行MD5加密
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        //设置员工创建时间, 修改时间,创建人,修改人

        //将传过来的密码进行加密处理



        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        employee.setCreateUser(empId);
        employee.setUpdateUser(empId);

        employeeService.save(employee);
        return R.success("添加成功");
    }

    /**
     * 修改员工信息
     * @param request
     * @param employee
     * @return
     */
    @PutMapping
    public R<String> update(HttpServletRequest request,@RequestBody Employee employee){
        log.info("修改的员工id:{}",employee.getId());

        String password = employee.getPassword();
        if(password!= null) {
            password = DigestUtils.md5DigestAsHex(password.getBytes());
        }

        //修改员工信息 修改时间 状态 修改人
        Long empId = (Long) request.getSession().getAttribute("empolyee");

        if("admin".equals(employeeService.getById(employee).getUsername())){
            throw new CustomException("管理员账号，禁止修改！");
        }
        if(employee.getId() == 1){
            throw new CustomException("管理员账号，禁止修改！");
        }

        employee.setPassword(password);
        employee.setUpdateUser(empId);
        employee.setUpdateTime(LocalDateTime.now());

        employeeService.updateById(employee);

        return R.success("修改员工信息成功");
    }

    /**
     * 根据id查询数据
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id){
        log.info("查询员工id:{}",id);
        //根据id查询数据
        Employee employee = employeeService.getById(id);

        employee.setPassword("123456");


        //判断数据是否为null 为null 返回异常
        if (employee == null){
            return R.error("查询失败");
        }
        //返回 数据
        //返回 数据
        return R.success(employee);
    }

}
